package com.fingard.dsp.bank.directbank.bos01;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Date;

import com.fingard.FGBiz;
import com.fingard.dsp.bank.reqrespobj.ReqRespHeader;
import com.fingard.dsp.bank.reqrespobj.elecbillquery.RetAtsB004BillFrontQry;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.bos01.util.GBKPostMethod;
import com.fingard.dsp.bank.directbank.bos01.util.SHAUtils;
import com.fingard.dsp.bank.directbank.bos01.util.SignOpStep;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class BOS01Base extends DirectBase implements ITcpClient {
    protected static final String INSERTSEQ = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,TRANSDATE,REQSEQID,BANKREQSEQID,BUSITYPE) values (?,?,?,?,?,?);";
    protected static final String SELECTSEQ = "SELECT BANKREQSEQID FROM REQSEQIDMAPPING WHERE REQSEQID=? AND BANKCODE=? AND BUSITYPE=?;";

    protected String getCharset() {
        return getBankConfig().getCharset("GBK");
    }

    private static TransIDHelper idHelper = new TransIDHelper(1, 999);
    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.DateTime12Year2Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }

    private String getBnkToken() {
        boolean isLoginValid = true;
        if (StringHelper.isNullOrEmpty(bankFront.token)) {
            isLoginValid = false;
        } else if (bankFront.lastVisitTime == null) {
            isLoginValid = false;
        } else {
            int timeOut = getBankConfig().getValueAsInt("sessionTimeOut");
            timeOut = timeOut <= 0 ? 10 : timeOut;
            Date currDate = new Date();
            if (DateHelper.getDifferMins(currDate, bankFront.lastVisitTime) > timeOut) {
                isLoginValid = false;
            } else if (DateHelper.compareDay(currDate, bankFront.lastVisitTime) != 0) {
                isLoginValid = false;
            }
        }

        if (!isLoginValid) {
            WriteBankLogLn("当前未登录前置或已登录超时，现在进行登录");
            login();

        }
        return bankFront.token;
    }

    protected void writeCommonHeader(XmlTextWriter xmlWriter, BOS01Header p_bankHeader) throws Exception {
        if (StringHelper.isNullOrEmpty(p_bankHeader.opName)) {
            throw new Exception("未赋值opName");
        }
        if (StringHelper.isNullOrEmpty(p_bankHeader.serialNo)) {
            throw new Exception("未赋值serialNo");
        }
        xmlWriter.writeStartDocument();
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
        xmlWriter.writeStartElement("BOSEBankData");
        xmlWriter.writeStartElement("opReq");
        xmlWriter.writeElementString("serialNo", p_bankHeader.serialNo);//地区
        if (p_bankHeader.reqTime == null) {
            p_bankHeader.reqTime = new Date();
        }
        xmlWriter.writeElementString("reqTime", Format.DateTime14Format.format(p_bankHeader.reqTime));
        if (p_bankHeader.writeParam) {
            xmlWriter.writeStartElement("ReqParam");
        }
    }

    protected void login() {
        try {
            int tmpMaxFailCount = getBankConfig().getValueAsInt("maxLoginFail");
            if (bankFront.loginFailCount >= tmpMaxFailCount) {
                WriteBankLogLn("登录失败次数" + bankFront.loginFailCount + "已达到上限，不再进行登录");
                return;
            }
            bankFront.lastLoginTime = new Date();
            bankFront.token = "";

            BOS01Header tmpHeader = new BOS01Header();
            tmpHeader.opName = "CebankUserLogon1_1Op";
            tmpHeader.serialNo = getQryTransID();
            tmpHeader.needSigned = true;

            XmlTextWriter xmlWriter = new XmlTextWriter();
            xmlWriter.autoFormat = false;
            writeCommonHeader(xmlWriter, tmpHeader);
            xmlWriter.writeElementString("userID", bankFront.loginName);
            xmlWriter.writeElementString("userPWD", bankFront.loginPasswd);
            xmlWriter.writeEndDocument();
            
            String[] tmpStrRet = sendToBankLogin(xmlWriter.toXmlString(), tmpHeader);
            
            if (tmpStrRet[0].length() == 0) {
                int flagIndex = tmpStrRet[1].indexOf("|");
                StringBuilder tmpSbMsg = new StringBuilder();

                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1].substring(flagIndex + 1, tmpStrRet[1].length()), tmpSbMsg);

                if (tmpBkReader != null) {
                    String tmprspcod = tmpBkReader.getFirstText("/BOSEBankData/opRep/retCode");
                    String tmprspmsg = tmpBkReader.getFirstText("/BOSEBankData/opRep/errMsg");
                    if (tmprspcod.equals("0") || tmprspcod.equals("2")) {
                        bankFront.token = tmpStrRet[1].substring(0, flagIndex);
                        bankFront.loginFailCount = 0;
                        WriteBankLogLn("登录成功");
                    } else {
                        bankFront.loginFailCount = bankFront.loginFailCount + 1;
                        WriteBankLogLn("登录失败：" + tmprspmsg);
                    }
                } else {
                    WriteBankLogLn("登录失败");
                }
            } else {
                WriteBankLogLn("登录失败：" + tmpStrRet[1]);
            }
        } catch (Exception e) {
            WriteBankLogLn("登录异常：" + e.getMessage());
            e.printStackTrace();
        }
    }

    private String generateSignPlain(String p_original) throws Exception {
        WriteBankLogLn2("需生成签名格式报文的原文为：" + p_original);
        XmlTextWriter xmlWriter = new XmlTextWriter();
        xmlWriter.writeStartDocByDeclaration("<?xml version=1.0 encoding=\"" + getCharset() + "\"?>");
        xmlWriter.writeStartElement("msg");
        xmlWriter.writeStartElement("msg_head");
        xmlWriter.writeElementString("msg_type", "0");
        xmlWriter.writeElementString("msg_id", "1005");
        xmlWriter.writeElementString("msg_sn", "0");
        xmlWriter.writeElementString("version", "1");
        xmlWriter.writeEndElement();
        xmlWriter.writeStartElement("msg_body");
        xmlWriter.writeElementString("origin_data_len", String.valueOf(p_original.getBytes(getCharset()).length));
        xmlWriter.writeElementString("origin_data", p_original);
        xmlWriter.writeEndDocument();
        return xmlWriter.toXmlString().replace("&lt;", "<").replace("&gt;", ">");
    }

    private boolean getSignedData(String p_reqStr, StringBuilder p_sb) {
        try {
            String p_signPlain = generateSignPlain(p_reqStr);
            WriteBankLogLn("提交银行进行签名的报文为：" + p_signPlain);
            WriteBankLogLn("进行签名的地址为：" + bankFront.serverIP + ":" + bankFront.signPort);
            TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(bankFront.signPort), this);
            TcpReceiver tmpReceiver = tmpClient.sendMessage(p_signPlain.getBytes(getCharset()));
            if (tmpReceiver.connState.equals(ConnState.FAIL)) {
                p_sb.append("签名通讯失败，请排查！");
                return false;
            }
            String retXmlStr = new String(tmpReceiver.recBytes, 0, tmpReceiver.readedLength, getCharset());
            WriteBankLogLn("签名返回报文：" + retXmlStr);
            XmlTextReader tmpBkReader = loadBankRespXmlReader(retXmlStr, p_sb);
            if (tmpBkReader != null) {
                if (tmpBkReader.read("/msg/msg_body/signed_data")) {
                    p_sb.append(tmpBkReader.readedXElement.innerText.replace("\r", "").replace("\n", ""));
                    return true;
                } else {
                    if (tmpBkReader.read("/msg/msg_body/error_no")) {
                        p_sb.append(String.format("签名失败，返回错误码：%s", tmpBkReader.readedXElement.innerText));
                    } else {
                        p_sb.append("签名失败，银行未返回错误码！");
                    }
                    return false;
                }

            } else {
                return false;
            }

        } catch (Exception ex) {
            p_sb.append(ex.getMessage());
            return false;
        }
    }

    protected String getSHAContent(String filePath, String serverIP, String signPort) throws Exception {
    	// 文件内容
		byte[] fileContent = FileHelper.readFileBytes(filePath);
		// 计算文件摘要
		byte[] shaByte = MessageDigest.getInstance("SHA-256").digest(fileContent);
		// 文件摘要16进制表示(大写)
		String hexStr = SHAUtils.byte2Hex(shaByte);
		// 签名字符串
		String singStr = SignOpStep.getNodeValue((new SignOpStep(hexStr)).sign(serverIP, signPort), "signed_data");
		// 上送银企的sha参数
		return SHAUtils.BOS_URLencode(singStr);
    }
    
    /**
	 * @param filePath
	 *            :文件绝对路径
     * @throws Exception
	 */
	public String[] uploadFile(String filePath, String reqSeqID, String payType) throws Exception {
		String[] tmpStrRet = new String[] {"",""};
		String sessionId = getBnkToken();
        if (StringHelper.isNullOrEmpty(sessionId)) {
        	tmpStrRet[0] = ConnState.FAIL;
        	tmpStrRet[1] = "自动登录失败，需先登录！";
            return tmpStrRet;
        }
		
		String serverUrl = bankFront.serverURL;
        String srvUrl = serverUrl.replace("http://", "").replace("https://", "");
        srvUrl = StringHelper.trimStart(srvUrl, "/");
        int indx = srvUrl.indexOf("/");
        if (indx > 0) {
            srvUrl = srvUrl.substring(0, indx);
        }
        String[] ipAndPort = srvUrl.split(":");
        
        String servletName = "";
        if ("ENDIIMPT".equals(payType)) {
        	servletName = "APIUploadWFFileServlet";
        } else if ("BatRec".equals(payType)) {
        	servletName = "APIUploadUNFileServlet";
        } else if ("BatPay".equals(payType)) {
        	servletName = "APIUploadBatchPayFileServlet";
        }
        
		String url = "http://" + ipAndPort[0] + ":" + ipAndPort[1] + "/CM/" + servletName + "?dse_sessionId=" + sessionId
				+ "&serialNo=" + reqSeqID;
		
		String sha = getSHAContent(filePath, bankFront.serverIP, bankFront.signPort);
		if ("BatPay".equals(payType)) {
			url+= "&sha=" + sha;
		}
		WriteBankLogLn("文件上传服务地址:\r\n" + url);
		HttpClient client = new HttpClient();
		GBKPostMethod mPost = new GBKPostMethod(url);
		mPost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "GBK");
		client.setParams(new HttpClientParams() {
			private static final long serialVersionUID = 1L;
			{
				setSoTimeout(300000);
			}
		});
		File file = new File(filePath);
		WriteBankLogLn("待上传文件路径:\r\n" + filePath);

		FilePart[] parts = { new FilePart("file", file) };
		MultipartRequestEntity isre = new MultipartRequestEntity(parts, mPost.getParams());
		mPost.setRequestEntity(isre);
		client.executeMethod(mPost);

		System.out.println(new String(mPost.getResponseBodyAsString().getBytes("GBK")));

		mPost.releaseConnection();
		tmpStrRet[1] = new String(mPost.getResponseBodyAsString().getBytes(mPost.getResponseCharSet()), "GBK");
		WriteBankLogLn("上传后响应数据:\r\n" + tmpStrRet[1]);
		return tmpStrRet;
	}
	
	 /**
	 * @param filePath
	 *            :文件绝对路径
     * @throws Exception
	 */
	public String[] uploadFile(String filePath, String reqSeqID, String payType, String areaFlag) throws Exception {
		String[] tmpStrRet = new String[] {"",""};
		String sessionId = getBnkToken();
        if (StringHelper.isNullOrEmpty(sessionId)) {
        	tmpStrRet[0] = ConnState.FAIL;
        	tmpStrRet[1] = "自动登录失败，需先登录！";
            return tmpStrRet;
        }
		
		String serverUrl = bankFront.serverURL;
        String srvUrl = serverUrl.replace("http://", "").replace("https://", "");
        srvUrl = StringHelper.trimStart(srvUrl, "/");
        int indx = srvUrl.indexOf("/");
        if (indx > 0) {
            srvUrl = srvUrl.substring(0, indx);
        }
        String[] ipAndPort = srvUrl.split(":");
        
        String servletName = "";
        if ("ENDIIMPT".equals(payType)) {
        	servletName = "APIUploadWFFileServlet";
        } else if ("BatRec".equals(payType)) {
        	servletName = "APIUploadUNFileServlet";
        } else if ("BatPay".equals(payType)) {
        	servletName = "APIUploadBatchPayFileServlet";
        } else if ("ForeignBatPay".equals(payType)) {
        	servletName = "APIUploadWHFileServlet";
        }
        
		String url = "http://" + ipAndPort[0] + ":" + ipAndPort[1] + "/CM/" + servletName + "?dse_sessionId=" + sessionId
				+ "&serialNo=" + reqSeqID;
		if ("ForeignBatPay".equals(payType)) {
			url+= "&areaFlag=" + areaFlag;
        }
		
		String sha = getSHAContent(filePath, bankFront.serverIP, bankFront.signPort);
		if ("BatPay".equals(payType) || "ForeignBatPay".equals(payType)) {
			url+= "&sha=" + sha;
		}
		WriteBankLogLn("文件上传服务地址:\r\n" + url);
		HttpClient client = new HttpClient();
		GBKPostMethod mPost = new GBKPostMethod(url);
		mPost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "GBK");
		client.setParams(new HttpClientParams() {
			private static final long serialVersionUID = 1L;
			{
				setSoTimeout(300000);
			}
		});
		File file = new File(filePath);
		WriteBankLogLn("待上传文件路径:\r\n" + filePath);

		FilePart[] parts = { new FilePart("file", file) };
		MultipartRequestEntity isre = new MultipartRequestEntity(parts, mPost.getParams());
		mPost.setRequestEntity(isre);
		client.executeMethod(mPost);

		System.out.println(new String(mPost.getResponseBodyAsString().getBytes("GBK")));

		mPost.releaseConnection();
		tmpStrRet[1] = new String(mPost.getResponseBodyAsString().getBytes(mPost.getResponseCharSet()), "GBK");
		WriteBankLogLn("上传后响应数据:\r\n" + tmpStrRet[1]);
		return tmpStrRet;
	}

	/**
	 * @param batchNo 批次号
	 * @param serialNo 序号
	 * @param type 类型
	 */
	public String[] downloadFile(String batchNo, String serialNo, String type, String payType) {
		String[] tmpStrRet = new String[] {"",""};
		String sessionId = getBnkToken();
        if (StringHelper.isNullOrEmpty(sessionId)) {
        	tmpStrRet[0] = ConnState.FAIL;
        	tmpStrRet[1] = "自动登录失败，需先登录！";
            return tmpStrRet;
        }
		
		String serverUrl = bankFront.serverURL;
        String srvUrl = serverUrl.replace("http://", "").replace("https://", "");
        srvUrl = StringHelper.trimStart(srvUrl, "/");
        int indx = srvUrl.indexOf("/");
        if (indx > 0) {
            srvUrl = srvUrl.substring(0, indx);
        }
        String[] ipAndPort = srvUrl.split(":");
        
        String url = "";
        if ("ENDIIMPT".equals(payType)) {
        	url = "http://" + ipAndPort[0] + ":" + ipAndPort[1] + "/CM/APIDownLoadWFFileServlet?dse_sessionId=" + sessionId
    				+ "&fileFlowNo=" + batchNo + "&serialNo=" + serialNo;
        } else if ("BatRec".equals(payType)) {
        	url = "http://" + ipAndPort[0] + ":" + ipAndPort[1] + "/CM/APIDownLoadUNFileServlet?dse_sessionId=" + sessionId
    				+ "&batchNo=" + batchNo + "&serialNo=" + serialNo + "&type=" + type;
        } else if ("BatPay".equals(payType)) {
        	String tmpBatNoPath = getTempFileDirectory() + File.separator + "Mapping" + File.separator + batchNo + ".txt";
        	WriteBankLogLn("本地批量代付银行批次号存取路径:" + tmpBatNoPath);
        	String tmpBatNo = FileHelper.readFileText(tmpBatNoPath, getCharset());
        	WriteBankLogLn("本地批量代付银行批次号内容:" + tmpBatNo);
        	String fileName = "HPWJ_" + Format.Date8Format.format(new Date()) + "_" + tmpBatNo + ".ret.txt";
        	url = "http://" + ipAndPort[0] + ":" + ipAndPort[1] + "/CM/APIDownLoadBatchPayFileServlet?dse_sessionId=" + sessionId
    				+ "&fileName=" + fileName + "&serialNo=" + serialNo + "&payAcct=";
        } else if ("ForeignBatPay".equals(payType)) {
        	url = "http://" + ipAndPort[0] + ":" + ipAndPort[1] + "/CM/APIDownLoadUNFileServlet?dse_sessionId=" + sessionId
    				+ "&batchNo=" + batchNo + "&type=" + type + "&serialNo=" + serialNo;
        }
        return download(url,payType);
	}

	public String[] download(String url,String transType){
        String[] tmpStrRet = new String[] {"",""};
        HttpClient client = new HttpClient();
        GetMethod httpGet = new GetMethod(url);
        WriteBankLogLn("文件下载服务地址:\r\n" + url);
        String fileName = null;
        InputStream in = null;
        BufferedInputStream br = null;
        ByteArrayOutputStream bouts = null;
        FileOutputStream out = null;

        try {
            client.executeMethod(httpGet);
            in = httpGet.getResponseBodyAsStream();
            Header header = httpGet.getResponseHeader("fileName");
            if (header == null || header.getValue() == null || "".equals(header.getValue())) {
                br = new BufferedInputStream(in);
                bouts = new ByteArrayOutputStream();
                byte[] b = new byte[4096];
                int len = 0;

                while ((len = br.read(b)) != -1) {
                    bouts.write(b, 0, len);
                }
                bouts.flush();
                tmpStrRet[1] = new String(bouts.toByteArray(), "GBK");
            } else {
                fileName = header.getValue();
                File file = new File(getTempFileDirectory() + File.separator + transType + File.separator + fileName);
                if (!file.exists()) {
                    File fileDir = new File(getTempFileDirectory() + File.separator + transType);
                    if (fileDir.mkdirs()) {
                        file.createNewFile();
                    }else{
                        WriteBankLogLn("创建目录失败:\r\n" + getTempFileDirectory() + File.separator + transType);
                    }
                }
                out = new FileOutputStream(file);

                byte[] b = new byte[4096];
                int len = 0;
                br = new BufferedInputStream(in);

                while ((len = br.read(b)) != -1) {
                    out.write(b, 0, len);
                }
                out.flush();
                tmpStrRet[1] = file.getAbsolutePath();
                WriteBankLogLn("下载文件成功,保存至本地路径为:\r\n" + file.getAbsolutePath());
                return tmpStrRet;
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            tmpStrRet[0] = "-1";
            tmpStrRet[1] = ex.getMessage();
            WriteBankLogLn(ex);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bouts != null) {
                try {
                    bouts.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            httpGet.releaseConnection();
        }
        return tmpStrRet;
    }

    public String[] downloadReceipt(String serialNo, String AccountNo, String queryDate, int zipCount) {
        String[] tmpStrRet = new String[] {"",""};
        String sessionId = getBnkToken();
        if (StringHelper.isNullOrEmpty(sessionId)) {
            tmpStrRet[0] = ConnState.FAIL;
            tmpStrRet[1] = "自动登录失败，需先登录！";
            return tmpStrRet;
        }

        String serverUrl = bankFront.serverURL;
        String srvUrl = serverUrl.replace("http://", "").replace("https://", "");
        srvUrl = StringHelper.trimStart(srvUrl, "/");
        int indx = srvUrl.indexOf("/");
        if (indx > 0) {
            srvUrl = srvUrl.substring(0, indx);
        }
        String[] ipAndPort = srvUrl.split(":");

	    String url = "http://" + ipAndPort[0] + ":" + ipAndPort[1] + "/CM/APIReceiptPdfDownLoadServlet?dse_sessionId=" + sessionId
                + "&serialNo=" + serialNo + "&AccountNo=" + AccountNo + "&queryDate=" + queryDate + "&zipCount=" + zipCount;
        return download(url,"DOWNRECEIPT");
    }



    protected String[] sendToBank(String p_reqStr, BOS01Header p_bankHeader) throws Exception {
    	String[] retStr = new String[]{"", ""};
    	
    	String tmpSendContent = p_reqStr;
        StringBuilder sb = new StringBuilder();
        if (p_bankHeader.needSigned) {
            boolean isSignedSuccess = getSignedData(p_reqStr, sb);
            if (isSignedSuccess) {
                tmpSendContent = sb.toString();
            } else {
                retStr[0] = ConnState.FAIL;
                retStr[1] = sb.toString();
                return retStr;
            }
        }

        String sessionID = getBnkToken();
        if (StringHelper.isNullOrEmpty(sessionID)) {
            retStr[0] = ConnState.FAIL;
            retStr[1] = "自动登录失败，需先登录！";
            return retStr;
        }

        bankFront.lastVisitTime = new Date();
        String url = bankFront.serverURL + "/CM/APIReqServlet";
        WriteBankLogLn("提交银行的地址：" + url);
        tmpSendContent = "dse_sessionId=" + bankFront.token + "&opName=" + p_bankHeader.opName + "&reqData=" + URLEncoder.encode(tmpSendContent, getCharset()).replace("%0a", "");
        WriteBankLogStep2(tmpSendContent);
        byte[] tmpToWriteBytes = tmpSendContent.getBytes(getCharset());
        WebRequest tmpWebRequest = new WebRequest(url);
        tmpWebRequest.setConnectTimeout(300000);
        tmpWebRequest.setReadTimeout(300000);
        tmpWebRequest.setRequestProperty("User-Agent", "MSIE");
        tmpWebRequest.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        tmpWebRequest.setRequestProperty("connection", "Close");
        tmpWebRequest.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        retStr = tmpWebRequest.upload(tmpToWriteBytes, getCharset());
        WriteBankLogStep3(retStr[1]);
        return retStr;
    }

    protected String[] sendToBankLogin(String p_reqStr, BOS01Header p_bankHeader) throws Exception {
        String tmpSendContent = p_reqStr;
        String[] retStr = new String[]{"", ""};
        StringBuilder sb = new StringBuilder();
        if (p_bankHeader.needSigned) {
            boolean isSignedSuccess = getSignedData(p_reqStr, sb);
            if (isSignedSuccess) {
                tmpSendContent = sb.toString();
            } else {
                retStr[0] = ConnState.FAIL;
                retStr[1] = sb.toString();
                return retStr;
            }
        }
        bankFront.lastVisitTime = new Date();
        String url = bankFront.serverURL + "/CM/APISessionReqServlet";
        WriteBankLogLn("提交银行的地址：" + url);
        tmpSendContent = "opName=" + p_bankHeader.opName + "&reqData=" + URLEncoder.encode(tmpSendContent, getCharset()).replace("%0a", "");
        WriteBankLogStep2(tmpSendContent);
        byte[] tmpToWriteBytes = tmpSendContent.getBytes(getCharset());
        WebRequest tmpWebRequest = new WebRequest(url);
        tmpWebRequest.setConnectTimeout(60000);
        tmpWebRequest.setRequestProperty("User-Agent", "MSIE");
        tmpWebRequest.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        tmpWebRequest.setRequestProperty("connection", "Close");
        retStr = tmpWebRequest.upload(tmpToWriteBytes, getCharset());
        WriteBankLogStep3(retStr[1]);
        return retStr;
    }
    
    public void getContentLength(TcpReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1) {
            String tmpCharset = getCharset();
            String tmpRecNow = new String(p_receiver.recBytes, 0, p_receiver.readedLength, tmpCharset);
            if (tmpRecNow.contains("</msg>")) {
                p_receiver.contentLength = p_receiver.readedLength;
                p_receiver.contentStartIndex = 0;
            }
        }
    }

    protected  String[] sendToATS(String jsonData) throws Exception{
        String[] retStr = new String[]{"",""};
        WriteBankLogLn("2.提交ATS的地址："+ FGBiz.dspCenter.dspSet.receiptPushServerUrl);

        //发送ATS
        WebRequest tmpRequest = new WebRequest(FGBiz.dspCenter.dspSet.receiptPushServerUrl);
        tmpRequest.setConnectTimeout(60000);
        tmpRequest.setRequestProperty("connection", "Close");
        tmpRequest.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        String charsetName = getCharset();
        WriteBankLogLn("3.推送给ATS的json数据"+jsonData);
        byte[] tmpWriteBytes = jsonData.getBytes(charsetName);
        retStr = tmpRequest.upload(tmpWriteBytes, charsetName);
        WriteBankLogLn("4.返回的数据"+retStr[1]);

        return retStr;
    }

    /**
     * 票据类型 1=AC01=银票  2=AC02=商票
     * @param billType
     * @return
     */
    protected String getBillType(String billType){
        String result="";
        if("AC01".equals(billType) || "AC02".equals(billType)){
            result= "AC01".equals(billType) ? "1" : "2";
        }else if("1".equals(billType) || "2".equals(billType)){
            result= "1".equals(billType) ? "AC01" : "AC02";
        }
        return result;
    }

    /**
     * 转让标志 1=EM00=可转让  0=EM01=不可转让
     * @param transFlag
     * @return
     */
    protected String getTransFlag(String transFlag){
        String result="";
        if("EM00".equals(transFlag) || "EM01".equals(transFlag)){
            result= "EM00".equals(transFlag) ? "1" : "0";
        }else if("1".equals(transFlag) || "0".equals(transFlag)){
            result= "1".equals(transFlag) ? "EM00" : "EM01";
        }
        return result;
    }

    /**
     * 清算标志 1=SM00=线上  2=SM01=线下
     * @param payType
     * @return
     */
    protected String getPayType(String payType){
        String result="";
        if("SM00".equals(payType) || "SM01".equals(payType)){
            result= "SM00".equals(payType) ? "1" : "2";
        }else if("1".equals(payType) || "2".equals(payType)){
            result= "1".equals(payType) ? "SM00" : "SM01";
        }
        return result;
    }

    /**
     * 签收标志  SU00同意签收  SU01拒绝签收
     * @param respFlag
     * @return
     */
    protected String getRespFlag(String respFlag){
        String result="";
        if("SU00".equals(respFlag) || "SU01".equals(respFlag)){
            result= "SU00".equals(respFlag) ? "1" : "2";
        }else if("1".equals(respFlag) || "2".equals(respFlag)){
            result= "1".equals(respFlag) ? "SU00" : "SU01";
        }
        return result;
    }

    /**
     * 获取拒付理由代码
     * DC00、与自己有直接债权债务关系的持票人未履行约定义务；
     * DC01、持票人以欺诈、偷盗或者胁迫等手段取得票据；
     * DC02、持票人明知有欺诈、偷盗或者胁迫等情形，出于恶意取得票据；
     * DC03、持票人明知债务人与出票人或者持票人的前手之间存在抗辩事由而取得票据；
     * DC04、持票人因重大过失取得不符合《票据法》规定的票据；
     * DC05、超过提示付款期；
     * DC06、被法院冻结或收到法院止付通知书；
     * DC07、票据未到期；
     * DC08、商业承兑汇票承兑人账户余额不足。
     * DC09、其他（必须注明）
     * @param unPayCode
     * @return
     */
    protected String getStddshnrcdByUnPayCode(String unPayCode){
        String stddshnrcd="";
        if ("99".equals(unPayCode)) {
            stddshnrcd="DC09";//拒付代码
        } else if (Integer.parseInt(unPayCode) > 0 && Integer.parseInt(unPayCode) <= 9) {
            stddshnrcd="DC0" + (Integer.parseInt(unPayCode) - 1);
        }
        return stddshnrcd;
    }

    /**
     * 付息方式:1：卖方付息;2：买方付息;3：协议付息
     * @param payInterestType
     * @return
     */
    protected String getPayInterestTypeToBank(String payInterestType) throws Exception{
        String result="";
        if(StringHelper.isNullOrEmpty(payInterestType)){
            result="02";//默认卖方付息
        }else {
            switch (Integer.parseInt(payInterestType)){
                case 1:result="02";break;
                case 2:result="01";break;
                case 3:result="03";break;
                default:throw new Exception("付息方式异常，请联系系统管理员");
            }
        }
        return result;
    }

    /**
     * 1-出票 2-承兑 3-收票 4-背书转让 5-质押 6-解质押
     * 7-出票保证 8-承兑保证 9-背书保证 10-贴现
     * 11-回购式贴现赎回 12-提示付款 13-追索 14-同意清偿
     * @param busiType
     * @return
     */
    protected String getBusiType(String busiType,String overdueFlag) throws Exception{
        String result="";
        switch (Integer.parseInt(busiType)){
            case 2:result="02";break;//可承兑
            case 3:result="03";break;//可收票
            case 4:result="05";break;//可背书
            case 5:result="15";break;//可质押
            case 6:result="16";break;//可质押解除
            case 7:result="14";break;//出票保证
            case 8:result="13";break;//承兑保证
            case 9:result="12";break;//背书保证
            case 10:result="06";break;//贴现
            case 12:
                if("1".equals(overdueFlag)){
                    result="17";//正常
                }else if("2".equals(overdueFlag)){
                    result="18";//逾期
                }break;//提示付款
            default:throw new Exception("银行暂不支持此业务类型");
        }
        return result;
    }

    /**
     * 签收业务映射
     * @param respType 1-承兑应答 2-收票应答 3-背书转让应答 4-回购式贴现赎回应答
     *                5-质押解除应答 6-提示付款应答 7-保证应答 8-同意清偿应,9-质押签收
     * @param proPayType  逾期标志 1非逾期 2逾期
     * @return
     */
    protected String getStdinfotypByRespType(String respType,String proPayType){
        String stdinfotyp="";
        if(StringHelper.hasAnyChar(respType)){
            switch (Integer.parseInt(respType)){
                case 1:stdinfotyp="02";break;//承兑签收
                case 2:stdinfotyp="03";break;//收票签收
                case 3:stdinfotyp="05";break;//背书签收
                //case 4:"";break;//回购式贴现赎回签收
                case 9:stdinfotyp="15";break;//质押签收
                case 5:stdinfotyp="16";break;//质押解除签收
                case 7:stdinfotyp="13";break;//14出票人提示保证签收、13承兑人提示保证签收、12背书人提示保证签收
                case 6:if("1".equals(proPayType)){
                    stdinfotyp="17";//非逾期提示付款签收
                }else if("2".equals(proPayType)){
                    stdinfotyp="18";//逾期提示付款签收
                }break;
                case 8:stdinfotyp="20";break;//同意清偿签收
                default:WriteBankLogLn("银行不支持此业务类型的签收");break;
            }
        }
        return stdinfotyp;
    }

    /**
     * 签收查询业务类型映射
     * @param busiType 1-出票 2-承兑 3-收票 4-背书转让 5-质押 6-解质押
     *                 7-出票保证 8-承兑保证 9-背书保证 10-贴现
     *                 11-回购式贴现赎回 12-提示付款 13-追索 14-同意清偿
     * @param overdueFlag  逾期标志 1非逾期 2逾期
     * @return
     */
    protected String getStdinfotypByBusiType(String busiType,String overdueFlag){
        String stdinfotyp="";
        if(StringHelper.hasAnyChar(busiType)){
            switch (Integer.parseInt(busiType)){
                case 2:stdinfotyp="02";break;//承兑签收
                case 3:stdinfotyp="03";break;//收票签收
                case 4:stdinfotyp="05";break;//背书签收
                case 5:stdinfotyp="15";break;//质押签收
                case 6:stdinfotyp="16";break;//质押解除签收
                case 7:stdinfotyp="14";break;//出票人提示保证签收
                case 8:stdinfotyp="13";break;//承兑人提示保证签收
                case 9:stdinfotyp="12";break;//背书人提示保证签收
                case 12:if("1".equals(overdueFlag)){
                            stdinfotyp="17";//非逾期提示付款签收
                        }else if("2".equals(overdueFlag)){
                            stdinfotyp="18";//逾期提示付款签收
                        }break;
                case 13:stdinfotyp="19";break;//追索通知签收
                case 14:stdinfotyp="20";break;//同意清偿签收
                default:WriteBankLogLn("银行不支持此业务类型的签收");break;
            }
        }
        return stdinfotyp;
    }

    /**
     * 获取票据操作日期
     * @param billNo
     * @return
     */
    protected String getBillStdDate(String billNo){
        String stdDate="";
        if(StringHelper.hasAnyChar(billNo) && billNo.length()>21){
            stdDate=billNo.substring(13,21);
        }
        return stdDate;
    }

    /**
     * 获取票据状态
     * @param actNum
     * @param billNo
     * @return
     * @throws Exception
     */
    protected String getBillStatus(String actNum,String billNo,ReqRespHeader reqRespHeader){
        RetAtsB004BillFrontQry retAts=null;
        try{
            retAts=getBillStatuByBillNoAnd04(actNum,billNo,reqRespHeader);
            if("-1".equals(retAts.respCode) || StringHelper.isNullOrEmpty(retAts.billState)){
                retAts=getBillStatuByBillNoAnd03(actNum,billNo,reqRespHeader);
            }
        }catch (Exception e){
            WriteBankLogLn("获取票据状态异常："+e.getMessage());
            return "";
        }
        if(retAts==null){
            return "";
        }
        return retAts.billState;
    }

    /**
     * 持票人票据信息查询
     * @param actNum
     * @param billNo
     * @return
     * @throws Exception
     */
    protected RetAtsB004BillFrontQry getBillStatuByBillNoAnd03(String actNum,String billNo,ReqRespHeader p_header) throws Exception{
        WriteBankLogLn("******************查询持票人票据信息******************");
        RetAtsB004BillFrontQry retAts = new RetAtsB004BillFrontQry(p_header);
        retAts.writeStart();
        String respCode = "";
        String respInfo ="";
        try{
            BOS01Header tmpHeader = new BOS01Header();
            tmpHeader.opName = "BillsForTicketQuery1_1Op";
            tmpHeader.serialNo = getQryTransID();
            tmpHeader.needSigned = true;
            XmlTextWriter xmlWriter = new XmlTextWriter();
            writeCommonHeader(xmlWriter, tmpHeader);
            xmlWriter.writeElementString("Stdqrycont", "",true);//查询内容
            xmlWriter.writeElementString("Stdsendflg", "03");//发起发标识
            xmlWriter.writeElementString("Stdappacct", actNum);//签约账号
            xmlWriter.writeElementString("Stdbillnum", billNo);//电子票号
            xmlWriter.writeElementString("Stdbegdate", "",true);//起始日期
            xmlWriter.writeElementString("Stdenddate", "",true);//结束日期
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), tmpHeader);
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmprspcod = tmpBkReader.getFirstText("/BOSEBankData/opRep/retCode");
                    String tmprspmsg = tmpBkReader.getFirstText("/BOSEBankData/opRep/errMsg");
                    if("0".equals(tmprspcod)){
                        String total=tmpBkReader.getFirstText("/BOSEBankData/opRep/opResult/Stdtotalnm");//总数
                        if("1".equals(total)){
                            while (tmpBkReader.read("/BOSEBankData/opRep/opResultSet/opResult")){
                                retAts.respCode= "0";
                                retAts.billNo=tmpBkReader.readedXElement.getSingleTextNotNull("Stdbillnum");//电子票据
                                retAts.billType=getBillType(tmpBkReader.readedXElement.getSingleTextNotNull("Stdbilltyp"));//票据类型 1-银承 2-商承
                                retAts.issDate=tmpBkReader.readedXElement.getSingleTextNotNull("Stdissdate");//出票日
                                retAts.dueDate=tmpBkReader.readedXElement.getSingleTextNotNull("Stdduedate");//到期日
                                retAts.billAmt=tmpBkReader.readedXElement.getSingleTextNotNull("Stdpmmoney");//电子票据金额
                                retAts.transFlag= getTransFlag(tmpBkReader.readedXElement.getSingleTextNotNull("Stdendormk"));//背书转让标识 1-可再转让 0-不得转让
                                retAts.mustPay= "1";//承兑无条件支付委托 1-无条件支付 0-非条件支付
                                retAts.drawName= tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwrnam");//出票人
                                retAts.drawCode= tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwrcod");//出票人组织代码
                                retAts.drawAct= tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwracc");//出票人账号
                                retAts.drawBnkName= tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwrbname");//出票人开户行行名
                                retAts.drawBnkCode= tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwrbnm");//出票人开户行行号
                                retAts.creditLv= tmpBkReader.readedXElement.getSingleTextNotNull("Stddrcdrat");//出票人信用等级
                                retAts.gradeAgent= tmpBkReader.readedXElement.getSingleTextNotNull("Stddrragcy");//出票人信用评级机构
                                retAts.gradeDueDate= tmpBkReader.readedXElement.getSingleTextNotNull("Stddrragcy");//出票人评级到期日
                                retAts.drGuarName= tmpBkReader.readedXElement.getSingleTextNotNull("Stddrguanm");//出票保证人名称
                                retAts.drGuarAddr= tmpBkReader.readedXElement.getSingleTextNotNull("Stddrguaad");//出票保证人地址
                                retAts.drGuarDate= tmpBkReader.readedXElement.getSingleTextNotNull("Stddrguadt");//出票保证日期
                                retAts.accpName= tmpBkReader.readedXElement.getSingleTextNotNull("Stdaccpnam");//承兑人名称
                                retAts.accpAct= tmpBkReader.readedXElement.getSingleTextNotNull("Stdaccpacc");//承兑人账号
                                retAts.accpBnkCode= tmpBkReader.readedXElement.getSingleTextNotNull("Stdaccpbnm");//承兑人开户行行号
                                retAts.accpCredit= tmpBkReader.readedXElement.getSingleTextNotNull("Stdaccprat");//承兑人信用等级
                                retAts.accpGradeDue= tmpBkReader.readedXElement.getSingleTextNotNull("Stdaccpdue");//承兑人评级到期日
                                retAts.apGuarName= tmpBkReader.readedXElement.getSingleTextNotNull("Stdacguanm");//承兑保证人名称
                                retAts.apGuarAddr= tmpBkReader.readedXElement.getSingleTextNotNull("Stdacguaad");//承兑保证人地址
                                retAts.apGuarDate= tmpBkReader.readedXElement.getSingleTextNotNull("Stdacguadt");//承兑保证日期
                                retAts.payeeName= tmpBkReader.readedXElement.getSingleTextNotNull("Stdpyeenam");//收款人名称
                                retAts.payeeAct= tmpBkReader.readedXElement.getSingleTextNotNull("Stdpyeeacc");//收款人账号
                                retAts.payeeBnkName= tmpBkReader.readedXElement.getSingleTextNotNull("Stdpyeebname");//收款人开户行行名
                                retAts.payeeBnkCode= tmpBkReader.readedXElement.getSingleTextNotNull("Stdpyeeacc");//收款人开户行行号
                                retAts.billState= tmpBkReader.readedXElement.getSingleTextNotNull("Stdbilstat");//票据状态
                            }
                        }
                    }else {
                        respCode="-1";
                        respInfo=tmprspmsg;
                    }
                }else {
                    respCode="-1";
                    respInfo=tmpSbMsg.toString();
                }
            }else {
                respCode="-1";
                respInfo=tmpStrRet[1];
            }
        }catch (Exception e){
            respCode="-1";
            respInfo=e.getMessage();
        }
        if("-1".equals(respCode)){
            retAts = new RetAtsB004BillFrontQry(p_header);
            retAts.writeStart();
            retAts.respCode =respCode;
            retAts.respInfo = respInfo;
        }
        retAts.writeRetDetail();
        retAts.writeEnd();
        WriteBankLogLn("******************查询持票人票据信息******************");
        return retAts;
    }

    /**
     * 票据经人查询
     * @param billNo
     * @return
     * @throws Exception
     */
    protected RetAtsB004BillFrontQry getBillStatuByBillNoAnd04(String actNum,String billNo,ReqRespHeader p_header) throws Exception{
        WriteBankLogLn("******************查询票据经人票据信息******************");
        RetAtsB004BillFrontQry retAts = new RetAtsB004BillFrontQry(p_header);
        retAts.writeStart();
        String respCode = "";
        String respInfo ="";
        try{
            BOS01Header tmpHeader = new BOS01Header();
            tmpHeader.opName = "BillsForTicketQuery1_1Op";
            tmpHeader.serialNo = getQryTransID();
            tmpHeader.needSigned = true;
            XmlTextWriter xmlWriter = new XmlTextWriter();
            writeCommonHeader(xmlWriter, tmpHeader);
            xmlWriter.writeElementString("Stdqrycont", "",true);//查询内容
            xmlWriter.writeElementString("Stdsendflg", "04");//发起发标识
            xmlWriter.writeElementString("Stdappacct", actNum);//签约账号
            xmlWriter.writeElementString("Stdbillnum", billNo);//电子票号
            xmlWriter.writeElementString("Stdbegdate", getBillStdDate(billNo),true);//起始日期
            xmlWriter.writeElementString("Stdenddate", getBillStdDate(billNo),true);//结束日期
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), tmpHeader);
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmprspcod = tmpBkReader.getFirstText("/BOSEBankData/opRep/retCode");
                    String tmprspmsg = tmpBkReader.getFirstText("/BOSEBankData/opRep/errMsg");
                    if("0".equals(tmprspcod)){
                        String total=tmpBkReader.getFirstText("/BOSEBankData/opRep/opResult/Stdtotalnm");//总数
                        if("1".equals(total)){
                            while (tmpBkReader.read("/BOSEBankData/opRep/opResultSet/opResult")){
                                retAts.respCode= "0";
                                retAts.billNo=tmpBkReader.readedXElement.getSingleTextNotNull("Stdbillnum");//电子票据
                                retAts.billType=getBillType(tmpBkReader.readedXElement.getSingleTextNotNull("Stdbilltyp"));//票据类型 1-银承 2-商承
                                retAts.issDate=tmpBkReader.readedXElement.getSingleTextNotNull("Stdissdate");//出票日
                                retAts.dueDate=tmpBkReader.readedXElement.getSingleTextNotNull("Stdduedate");//到期日
                                retAts.billAmt=tmpBkReader.readedXElement.getSingleTextNotNull("Stdpmmoney");//电子票据金额
                                retAts.transFlag= getTransFlag(tmpBkReader.readedXElement.getSingleTextNotNull("Stdendormk"));//背书转让标识 1-可再转让 0-不得转让
                                retAts.mustPay= "1";//承兑无条件支付委托 1-无条件支付 0-非条件支付
                                retAts.drawName= tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwrnam");//出票人
                                retAts.drawCode= tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwrcod");//出票人组织代码
                                retAts.drawAct= tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwracc");//出票人账号
                                retAts.drawBnkName= tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwrbname");//出票人开户行行名
                                retAts.drawBnkCode= tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwrbnm");//出票人开户行行号
                                retAts.creditLv= tmpBkReader.readedXElement.getSingleTextNotNull("Stddrcdrat");//出票人信用等级
                                retAts.gradeAgent= tmpBkReader.readedXElement.getSingleTextNotNull("Stddrragcy");//出票人信用评级机构
                                retAts.gradeDueDate= tmpBkReader.readedXElement.getSingleTextNotNull("Stddrragcy");//出票人评级到期日
                                retAts.drGuarName= tmpBkReader.readedXElement.getSingleTextNotNull("Stddrguanm");//出票保证人名称
                                retAts.drGuarAddr= tmpBkReader.readedXElement.getSingleTextNotNull("Stddrguaad");//出票保证人地址
                                retAts.drGuarDate= tmpBkReader.readedXElement.getSingleTextNotNull("Stddrguadt");//出票保证日期
                                retAts.accpName= tmpBkReader.readedXElement.getSingleTextNotNull("Stdaccpnam");//承兑人名称
                                retAts.accpAct= tmpBkReader.readedXElement.getSingleTextNotNull("Stdaccpacc");//承兑人账号
                                retAts.accpBnkCode= tmpBkReader.readedXElement.getSingleTextNotNull("Stdaccpbnm");//承兑人开户行行号
                                retAts.accpCredit= tmpBkReader.readedXElement.getSingleTextNotNull("Stdaccprat");//承兑人信用等级
                                retAts.accpGradeDue= tmpBkReader.readedXElement.getSingleTextNotNull("Stdaccpdue");//承兑人评级到期日
                                retAts.apGuarName= tmpBkReader.readedXElement.getSingleTextNotNull("Stdacguanm");//承兑保证人名称
                                retAts.apGuarAddr= tmpBkReader.readedXElement.getSingleTextNotNull("Stdacguaad");//承兑保证人地址
                                retAts.apGuarDate= tmpBkReader.readedXElement.getSingleTextNotNull("Stdacguadt");//承兑保证日期
                                retAts.payeeName= tmpBkReader.readedXElement.getSingleTextNotNull("Stdpyeenam");//收款人名称
                                retAts.payeeAct= tmpBkReader.readedXElement.getSingleTextNotNull("Stdpyeeacc");//收款人账号
                                retAts.payeeBnkName= tmpBkReader.readedXElement.getSingleTextNotNull("Stdpyeebname");//收款人开户行行名
                                retAts.payeeBnkCode= tmpBkReader.readedXElement.getSingleTextNotNull("Stdpyeeacc");//收款人开户行行号
                                retAts.billState= tmpBkReader.readedXElement.getSingleTextNotNull("Stdbilstat");//票据状态
                            }
                        }
                    }else {
                        respCode="-1";
                        respInfo=tmprspmsg;
                    }
                }else {
                    respCode="-1";
                    respInfo=tmpSbMsg.toString();
                }
            }else {
                respCode="-1";
                respInfo=tmpStrRet[1];
            }
        }catch (Exception e){
            respCode="-1";
            respInfo=e.getMessage();
        }
        if("-1".equals(respCode)){
            retAts = new RetAtsB004BillFrontQry(p_header);
            retAts.writeStart();
            retAts.respCode =respCode;
            retAts.respInfo = respInfo;
        }
        retAts.writeRetDetail();
        retAts.writeEnd();
        WriteBankLogLn("******************查询票据经人票据信息******************");
        return retAts;
    }
}
